<?php
namespace Common\Model;

class AdStatsModel extends Model {
    protected $tableName = 'template.ad_stats';
    protected $viewName  = 'v_ad_stats';
    protected $pk        = 'id';

    /**
     * _parseOptions
     * 拦截_parseOptions主要是为了自动生成表名
     * 生成表名时必须用到的参数有day
     *
     * @param mixed $options
     * @return void
     */
    protected function _parseOptions($options = null) {
        if(empty($this->trueTableName) || ($this->trueTableName == $this->tableName)) {
            $day = empty($this->options['where']['day']) ? null : $this->options['where']['day'];

            if(empty($day)) {
                throw new ThinkException('请确认是否有day');
            }

            $timestamp  = strtotime($day);
            $tableName  = 'd' . date('Ymd', $timestamp) . '.'. $this->viewName;
            $options    = array_merge($options, array('table' => $tableName));

            $this->trueTableName = $tableName;
        }

        if (isset($options['where']['day'])) {
            unset($options['where']['day']);    //表中无day字段，用day主要是定位到对应日期的表上
        }

        if (isset($this->options['where']['day'])) {
            unset($this->options['where']['day']);    //表中无day字段，用day主要是定位到对应日期的表上
        }

        return parent::_parseOptions($options);
    }

    /**
     * buildSearchExpr 
     * 组装查询条件
     * 
     * @param mixed $d  查询数据，一般来源于$_GET或$_POST
     * @param mixed $field  可查询的字段对照表，其结构为array(array('表单项目名称' => '数据库字段名称'))
     * @access public
     * @return void 返回值为数组，参见方法内部注释
     */
    public function buildSearchExpr($d, $field = NULL) {
        $expr = array();
        $dao  = array();
        $sortExpr = 'view DESC';

        /**
         * 下标为表单中的项目名称，值为数据库中表的字段名称 
         */
        if(empty($field)) {
            $field  =   array(
                'day'     => 'day',
                'ad_id'   => 'ad_id',
                'plan_id' => 'plan_id',
            );
        }

        foreach($field as $k => $v) {
            $tmpExpr = null;
            $val     = isset($d[$k]) ? trim($d[$k]) : '';

            if(strlen($val) < 1) {
                continue;
            }

            if($k == 'day') {
                $day         = strtotime($val) ? $val : date('Y-m-d');
                $expr['day'] = $day;
            } else {
                $expr[$v] = $d[$k];
            }

            if(!empty($tmpExpr)) {
                $expr['_string'] = empty($expr['_string'])
                                  ? $tmpExpr
                                  : $expr['_string'] . " AND {$tmpExpr}";
            }

            $dao[$k] = $d[$k];
        }

        if(empty($expr['day'])) {
            $expr['day'] = date('Y-m-d');
            $dao['day']  = $expr['day'];
        }

        if(!empty($d['sort'])) {
            $sortdir   = empty($d['sortdir'])                     ? 'DESC'   : strtoupper($d['sortdir']);
            $sortdir   = in_array($sortdir, array('DESC', 'ASC')) ? $sortdir : 'DESC';
            $sortField = $d['sort'];

            if ($sortField == 'ctr') {
                $sortField = 'round((num::numeric / view::numeric) * 100, 2)';    //postgresql中除法如果需要返回小数，那么参数运算的数都必须转换成小数
            }

            $sortExpr       = "{$sortField} {$sortdir}";
            $dao['sort']    = $d['sort'];
            $dao['sortdir'] = $sortdir;
        }

        if(empty($expr) && empty($dao)) {
            return false;
        }

        return array(
            'expr' => $expr,            //ThinkPHP查询条件表达式
            'sort' => $sortExpr,        //排序表达式
            'json' => json_encode($dao) //用于回填至查询表单的数据
        );
    }

    protected function _options_filter(&$options) {
        if(!$loginUser = C('RUN_LOGIN_USER')) {
            exit('NO LOGIN');
        }

        /**
         * 为广告主平台数据绑定广告主编号
         */
        if($loginUser['type'] == 2) {
            $planId = I('get.plan_id', 0, 'intval');
            $mPlan  = D2('Plan');

            /**
             * 如果找不到对应的计划信息，则将条件中的plan_id改成零，这样就可以达到阻止后续查询的目的
             * 因为不存在plan_id=0的数据
             */
            if(!$mPlan->getByPlanId($planId)) {
                $options['where']['plan_id'] = 0;

                return false;
            }
        }
    }

}
